import {EditorState} from "prosemirror-state"
import {EditorView} from "prosemirror-view"
import {Schema, DOMParser, DOMSerializer} from "prosemirror-model"
import {exampleSetup} from "prosemirror-example-setup"
let _view
const schema = new Schema({
  nodes: {
    doc: {
      content: "block+"
    },
    // Custom paragraph rendered as <p class="custom-paragraph">
    customParagraph: {
      group: "block",
      content: "text*",
      // parseDOM: [
      //   {tag: "p[data-node-type=custom-paragraph]"},
      //   {
      //     tag: "p",
      //     getAttrs(dom) {
      //       return dom.classList.contains("custom-paragraph") ? null : false
      //     }
      //   }
      // ],
      toDOM(node,t) {
        console.log(_view);
        console.log(this);
        if(_view) {
          const domNodes = document.querySelectorAll('.custom-paragraph')
          const targetDom = domNodes[0]
          if(targetDom) {
            const pos = _view.domAtPos(targetDom).offset
            console.log(pos);
            const domNode = _view.domAtPos(pos)
            console.log(domNode);
          }
        }
        // a.j 中的 e= node t prosemirror 中没有，应该是自定义的
        console.log('toDOM')
        // node 
        console.log(node)
        // return ["div", {"data-node-type": "custom-paragraph", class: "custom-paragraph"}, 0]
        return this.toRenderDOM(node)
      },
      toRenderDOM(node) {
        console.log('toRenderDOM')
        return ["p", {"data-node-type": "custom-paragraph", class: "custom-paragraph torenderdom-func"}, 0]
      }
    },
    text: {
      group: "inline"
    }
  }
})

const serializer = DOMSerializer.fromSchema(schema)
console.log(serializer)
export function initEditor(domSelector, contentSelector) {
  const mountEl = document.querySelector(domSelector)
  if (!mountEl) {
    throw new Error(`Mount element not found for selector ${domSelector}`)
  }

  const contentRoot = document.querySelector(contentSelector)
  const doc = contentRoot
    ? DOMParser.fromSchema(schema).parse(contentRoot)
    : schema.topNodeType.createAndFill()

  const view = new EditorView(mountEl, {
    state: EditorState.create({
      doc: doc || schema.topNodeType.create(),
      plugins: exampleSetup({schema})
    })
  })
  _view = view
  console.log(view)
  console.log(view.state.toJSON())
  console.log(view.state.doc)
  return {
    schema,
    view,
  }
}
